package cn.kow.kmall.controller.system;

import cn.kow.kmall.admin.pojo.vo.SysUserVO;
import cn.kow.kmall.controller.BaseController;
import cn.kow.kmall.core.constant.KmallStatusConstant;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.system.entity.SysMenu;
import cn.kow.kmall.system.entity.SysRole;
import cn.kow.kmall.system.entity.SysUser;
import cn.kow.kmall.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-10-29 17:04
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/info")
    public KmallResult info() {
        SysUser user = currentUser();
        List<SysRole> roleList = user.getRoles();
        List<String> roles = roleList.stream().map(role -> role.getRoleCode()).collect(Collectors.toList());
        List<String> permissions = new ArrayList<>();
        if (roles.contains("admin")) {
            permissions.add("*:*:*");
        } else {
            for (SysRole role : roleList) {
                List<SysMenu> menus = role.getMenus();
                if (CollectionUtils.isEmpty(menus)) {
                    continue;
                }
                menus.stream().forEach(m -> permissions.add(m.getPerms()));
            }
        }
        return KmallResult.success()
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("roles", roles)
                .put("permissions", permissions);
    }

    /**
     * 获取菜单列表
     *
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public KmallResult list(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String phone,
                           @RequestParam(required = false) Short status,
                           @PageableDefault(sort = {"id"}, direction = Sort.Direction.ASC) Pageable pageable) {
        Page<SysUser> userPage = sysUserService.listUserByPage(username, phone, status, pageable);
        List<SysUserVO> list = userPage.getContent().stream().map(m -> toUserVO(m)).collect(Collectors.toList());
        return KmallResult.success().put("rows", list)
                .put("total", userPage.getTotalElements());
    }

    private SysUserVO toUserVO(SysUser sysUser) {
        SysUserVO userVO = new SysUserVO();
        BeanUtils.copyProperties(sysUser, userVO);
        userVO.setUserId(sysUser.getId());
        if (KmallStatusConstant.DISABLE.equals(sysUser.getStatus())) {
            userVO.setLocked(true);
        } else {
            userVO.setLocked(false);
        }
        return userVO;
    }

    @PostMapping("/add")
    public KmallResult add(@RequestBody SysUser user) {
        if (StringUtils.isEmpty(user.getPassword())) {
            return KmallResult.fail("密码不能为空");
        }

        String encodePwd = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePwd);
        sysUserService.save(user);
        return KmallResult.success();
    }

    @DeleteMapping("/{userId}")
    public KmallResult delete(@PathVariable Long userId) {
        sysUserService.remove(userId);
        return KmallResult.success();
    }

    @PostMapping("/edit")
    public KmallResult edit(@RequestBody SysUser user) {
        sysUserService.update(user);
        return KmallResult.success();
    }

    @GetMapping("/enable")
    public KmallResult enable(@RequestParam Long userId) {
        sysUserService.enableUser(userId);
        return KmallResult.success();
    }

    @GetMapping("/lock")
    public KmallResult lock(@RequestBody Long userId) {
        sysUserService.lockUser(userId);
        return KmallResult.success();
    }

    @GetMapping("/unlock")
    public KmallResult unlock(@RequestParam Long userId) {
        sysUserService.unlockUser(userId);
        return KmallResult.success();
    }
}

